"""this script parse the content of a xml file"""
import serial
import serial.tools.list_ports


class Ser():
    """ Summary of class here.
    串口类
    """

    def __init__(self):
        """
        串口初始化
        """
        self.is_opened = False
        self.plist_len = 0

    def open(self, serial_name, parity_bit='N', baud_rate=115200):
        """
        打开串口
        :param :略
        :return:True:成功,False:失败
        """
        serial_hanlde = None
        try:
            serial_hanlde = serial.Serial(
                port=serial_name, baudrate=baud_rate, bytesize=8, parity=parity_bit, stopbits=1, timeout=0.5)
            self.is_opened = True
            return serial_hanlde
        except (IOError, ValueError):
            return serial_hanlde

    def close(self, serial_hanlde):
        """
        关闭串口
        :param :None
        :return:None
        """
        if serial_hanlde is None:
            return False
        self.is_opened = serial_hanlde.isOpen()
        if self.is_opened:
            serial_hanlde.close()
            return True
        return False

    def write(self, serial_hanlde, data):
        """
        写数据到串口
        :param data:数据
        :return:True:成功,False:失败
        """
        if serial_hanlde is None:
            return False
        self.is_opened = serial_hanlde.isOpen()
        if self.is_opened:
            serial_hanlde.write(bytes(data))
            return True
        return False

    def read(self, serial_hanlde):
        """
        读串口所有数据
        :param data_type:根据需要选择数据类型
        :return response:读到的数据
        """
        response = b''
        if serial_hanlde is None:
            return response
        self.is_opened = serial_hanlde.isOpen()
        if self.is_opened:
            response = serial_hanlde.readall()
        return response

    def readline(self, serial_hanlde):
        """
        读串口单行数据
        :param data_type:根据需要选择数据类型
        :return response:读到的数据
        """
        response = b''
        if serial_hanlde is None:
            return response
        self.is_opened = serial_hanlde.isOpen()
        if self.is_opened:
            response = serial_hanlde.readline()
        return response

    def search(self):
        """
        搜索串口设备
        :param :None
        :return serial_hanlde:串口句柄
        """
        serial_hanlde = []
        plist = list(serial.tools.list_ports.comports())
        self.plist_len = len(plist)
        if self.plist_len > 0:
            for i in range(self.plist_len):
                plist_0 = list(plist[i])
                serial_hanlde.append(plist_0)
        return serial_hanlde


if __name__ == '__main__':
    pass
